package com.chaofan.controller;

import com.chaofan.controller.support.UserSupport;
import com.chaofan.domain.R;
import com.chaofan.domain.User;
import com.chaofan.service.UserService;
import com.chaofan.util.RSAUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

/**
 * @author 李超凡
 * @since 2022/1/14 17:30
 */
@RestController
public class UserController {

    private UserService userService;

    private UserSupport userSupport;

    @Autowired
    public void setUserService(UserService userService) {
        this.userService = userService;
    }

    @Autowired
    public void setUserSupport(UserSupport userSupport) {
        this.userSupport = userSupport;
    }

    @GetMapping("/users")
    public R<User> getUserInfo(){
        Long userId = userSupport.getCurrentUserId();
        User user = userService.getUserInfo(userId);
        return new R<>(user);
    }

    @GetMapping("/rsa-pks")
    public R<String> getRsaPublicKey() {
        return R.success(RSAUtil.getPublicKeyStr());
    }

    @PostMapping("/users")
    public R<String> addUser(@RequestBody User user) {
        userService.addUser(user);
        return R.success();
    }

    @PostMapping("/user-tokens")
    public R<String> login(@RequestBody User user) throws Exception {
        String token = userService.login(user);
        return R.success(token);
    }

    @PutMapping("/users")
    public R<String> updateUser(@RequestBody User user) {
        Long currentUserId = userSupport.getCurrentUserId();
        user.setId(currentUserId);
        userService.updateUser(user);
        return R.success();
    }
}
